import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getUserTempId } from './tools'

import store from '@/store/index'

const request = axios.create({
  baseURL: '/api', // 1. 复用请求地址前缀
  timeout: 10000 // 请求超时时间
})
// 请求拦截器
request.interceptors.request.use(
  // 成功
  (config) => {
    NProgress.start()

    const token = store.state.user.token

    if (token) {
      config.headers.token = token
    } else {
      config.headers.userTempId = getUserTempId()
    }
    return config
  }
  // 失败
  // () => {}
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    NProgress.done()
    // response就是服务器的响应结果
    if (response.data.code === 200) {
      return response.data.data
    } else {
      // 功能失败
      alert(response.data.message)
      return Promise.reject(response.data.message)
    }
  },
  // 请求失败 - 失败
  (error) => {
    NProgress.done()
    alert(error)
    return Promise.reject(error)
  }
)

export default request
